const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
require('dotenv').config();

async function importDatabase() {
  let connection;
  
  try {
    console.log('🚀 开始导入数据库结构...\n');
    
    // 显示配置信息
    console.log('📋 数据库配置:');
    console.log(`   主机: ${process.env.DB_HOST}`);
    console.log(`   端口: ${process.env.DB_PORT}`);
    console.log(`   用户: ${process.env.DB_USER}`);
    console.log(`   数据库: ${process.env.DB_NAME}\n`);
    
    // 创建数据库连接
    console.log('🔌 正在连接数据库...');
    connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      port: process.env.DB_PORT || 3306,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      charset: 'utf8mb4',
      multipleStatements: true  // 允许执行多条SQL语句
    });
    
    console.log('✅ 数据库连接成功\n');
    
    // 读取SQL文件
    const sqlPath = path.join(__dirname, '../database/linkmate_schema.sql');
    console.log(`📖 正在读取SQL文件: ${sqlPath}`);
    
    if (!fs.existsSync(sqlPath)) {
      throw new Error(`SQL文件不存在: ${sqlPath}`);
    }
    
    const sqlContent = fs.readFileSync(sqlPath, 'utf8');
    console.log(`✅ SQL文件读取成功 (${(sqlContent.length / 1024).toFixed(2)} KB)\n`);
    
    // 检查当前表数量
    const [tablesBefore] = await connection.execute(
      "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ?",
      [process.env.DB_NAME]
    );
    console.log(`📊 导入前表数量: ${tablesBefore[0].count}\n`);
    
    // 执行SQL
    console.log('⚙️  正在执行SQL语句（这可能需要一些时间）...');
    console.log('   请稍候...\n');
    
    const startTime = Date.now();
    await connection.query(sqlContent);
    const endTime = Date.now();
    
    console.log(`✅ SQL执行完成 (耗时: ${((endTime - startTime) / 1000).toFixed(2)} 秒)\n`);
    
    // 检查导入后的表数量
    const [tablesAfter] = await connection.execute(
      "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = ?",
      [process.env.DB_NAME]
    );
    console.log(`📊 导入后表数量: ${tablesAfter[0].count}`);
    console.log(`📈 新增表数量: ${tablesAfter[0].count - tablesBefore[0].count}\n`);
    
    // 列出所有表
    const [tableList] = await connection.execute(
      "SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE' ORDER BY table_name",
      [process.env.DB_NAME]
    );
    
    if (tableList.length > 0) {
      console.log('📋 数据库表列表:');
      tableList.forEach((table, index) => {
        console.log(`   ${(index + 1).toString().padStart(2, ' ')}. ${table.table_name}`);
      });
    }
    
    console.log('\n✅ 数据库导入完成！');
    return true;
    
  } catch (error) {
    console.error('\n❌ 数据库导入失败！');
    console.error(`   错误代码: ${error.code}`);
    console.error(`   错误信息: ${error.message}`);
    
    if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.error('\n💡 提示: 数据库访问被拒绝，请检查用户名和密码');
    } else if (error.code === 'ER_BAD_DB_ERROR') {
      console.error('\n💡 提示: 数据库不存在，请先创建数据库');
    } else if (error.code === 'ECONNREFUSED') {
      console.error('\n💡 提示: 无法连接到数据库服务器');
    } else if (error.sqlMessage) {
      console.error(`   SQL错误: ${error.sqlMessage}`);
    }
    
    return false;
  } finally {
    if (connection) {
      await connection.end();
      console.log('\n🔌 数据库连接已关闭');
    }
  }
}

// 运行导入
importDatabase()
  .then((success) => {
    process.exit(success ? 0 : 1);
  })
  .catch((error) => {
    console.error('导入过程中发生错误:', error);
    process.exit(1);
  });

